package com.ocom.payhandle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.card.EntityXfRepairpayConfig;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoXfRepairpayConfig;
import com.ocom.payhandle.service.XfRepairpayConfigService;
import com.ocom.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class XfRepairpayConfigServiceImpl extends ServiceImpl<IDaoXfRepairpayConfig, EntityXfRepairpayConfig> implements XfRepairpayConfigService {

    @Autowired
    private IDaoXfRepairpayConfig iDaoXfRepairpayConfig;


    @Resource
    private RedisUtil redisUtil;

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB)
    public EntityXfRepairpayConfig getByComId(Long comId,Long merchId) {
        String canKey = "xf_repairpay_config#comId:"+ comId +"#merchId:"+ merchId;
        Object entityXfRepairpayConfigObj  =  redisUtil.get(canKey);
        EntityXfRepairpayConfig entityXfRepairpayConfig = null;
        if (entityXfRepairpayConfigObj == null) {
            QueryWrapper<EntityXfRepairpayConfig> queryWrapper = Wrappers.query();
            queryWrapper.eq("com_id", comId);
            queryWrapper.eq("status", 1);
            if(merchId == null) merchId = 0l;
            Long finalMerchId = merchId;
            queryWrapper.and(wrapper -> wrapper.isNull("merch_ids").or().eq("merch_ids","").or().apply( "find_in_set( " + finalMerchId + ", merch_ids )"));
            entityXfRepairpayConfig =  this.getOne(queryWrapper);
            if (entityXfRepairpayConfig != null) {
                redisUtil.set(canKey, entityXfRepairpayConfig, 60l * 60l * 4l);
            } else {
                redisUtil.set(canKey, "null", 60l * 60l * 4l);
            }
        } else {
            if (entityXfRepairpayConfigObj.toString().equals("null")) {
                return null;
            }
            entityXfRepairpayConfig = (EntityXfRepairpayConfig) entityXfRepairpayConfigObj;
        }
        return entityXfRepairpayConfig;
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB)
    public List<EntityXfRepairpayConfig> getListByStatus(Integer status) {
        QueryWrapper<EntityXfRepairpayConfig> queryWrapper = Wrappers.query();
        queryWrapper.eq("status", status);
        return this.list(queryWrapper);
    }
}
